<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row>
        <el-col :span="12">
          <div class="search-condition-div">
            <el-form-item label="跟进状态:" prop="followStatus">
              <span
                v-for="(item, index) in followupstatusData"
                :key="index"
                @click="changefollowupstatusColor(item,index)"
                :class="'1' === item.checked ? 'active' : ''"
              >
                {{ item.name }}
              </span>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="search-condition-div">
            <el-form-item label="渠道:" prop="channel">
              <span
                v-for="(item, index) in channelData"
                :key="index"
                @click="changechannelColor(item,index)"
                :class="'1' === item.checked ? 'active' : ''"
              >
                {{ item.name }}
              </span>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="search-condition-div">
            <el-form-item label="线索来源:" prop="cluesSources">
              <span
                  v-for="(item, index) in cluesourcesData"
                  :key="index"
                @click="changecluesourcesColor(item,index)"
                  :class="'1' === item.checked ? 'active' : ''"
                >
                {{ item.name }}
              </span>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="search-condition-div">
            <el-form-item label="责任人:" prop="head">
              <el-select v-model="queryParams.heads" @change="headChanged" multiple placeholder="请选择责任人">
                <el-option
                  v-for="item in userOptions"
                  :key="item.userName"
                  :label="item.nickName"
                  :value="item.userName"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="归属部门:" prop="deptId">
            <treeselect 
              style="float:left;width:220px;" 
              :multiple="true" 
              v-model="queryParams.deptIds" 
              :options="deptOptions" 
              @deselect="deSelectPatenteeidsDept"
              @select="selectPatenteeidsDept"
              :show-count="true" placeholder="请选择归属部门" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="search-condition-div">
            <el-form-item label="跟进时间:" prop="realityFollowRecordsSearch">
              <span
                v-for="(item, index) in followuptimeData"
                :key="index"
                @click="changefollowuptimeColor(item,index)"
                :class="'1' === item.checked ? 'active' : ''"
              >
                {{ item.name }}
              </span>
              <el-date-picker
                clearable 
                v-model="queryParams.realityFollowRecordsSearch" 
                placeholder="请选择"
                unlink-panels
                :value="timeArr"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                :picker-options="pickerOptions"
                @input="change($event)"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="全部线索" name="all" v-if="checkPermi(['crm:clue:query'])">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['crm:clue:add']" >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['crm:clue:edit']" >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['crm:clue:remove']" >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['crm:clue:export']" >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getAllList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="allClueList" @selection-change="handleSelectionChange" @cell-mouse-enter="cellMouseEnter" @cell-mouse-leave="cellMouseLeave">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键id" align="center" prop="id" v-if="false"/>
          <el-table-column label="姓名" align="left" prop="name" width="80" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                <a target="_blank" style="color:#007bff;" v-if="scope.row.id!=null" @click="detailReport(scope.row.id)"> {{ scope.row.name }} </a>
                <span v-else> {{ scope.row.name }} </span>
            </template>
          </el-table-column>
          <el-table-column label="手机" align="center" prop="phone" width="150"/>
          <el-table-column label="跟进状态" align="left" prop="followStatus" width="110"/>
          <el-table-column label="线索来源" align="center" prop="cluesSources" width="100"/>
          <el-table-column label="责任人" align="center" prop="head" width="160"/>
          <el-table-column label="部门" align="center" prop="deptName" width="100" :show-overflow-tooltip="true"/>
          <el-table-column label="前负责人" align="center" prop="formerHead"  v-if="false"/>
          <el-table-column label="前所属部门" align="center" prop="formerDept"  v-if="false"/>
          <el-table-column label="最新跟进记录" align="left" prop="latestFollowRecords" width="240">
            <template slot-scope="scope">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" v-if="scope.row.hoverFlag" @click="addFollowRecords(scope.row)" v-hasPermi="['crm:clue:add']" >写跟进</el-button>
              <span v-else> {{ scope.row.latestFollowRecords}} </span>
            </template>
          </el-table-column>
          <el-table-column label="实际跟进记录" align="center" prop="realityFollowRecords" width="160" v-if="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.realityFollowRecords, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="未跟进天数" align="center" prop="notFollowDays" />
          <el-table-column label="下次跟进时间" align="center" prop="nextFollowTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.nextFollowTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="渠道" align="center" prop="channel" />
          <el-table-column label="转客户时间" align="center" prop="transferCustomerTime" width="120" v-if="false">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.transferCustomerTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最后通话时间" align="center" prop="lastCallTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastCallTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['crm:clue:edit']" >修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['crm:clue:remove']" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getAllList"/>
      </el-tab-pane>
      <el-tab-pane label="我的线索" name="my">
        <el-table v-loading="loading" :data="myClueList" @selection-change="handleSelectionChange" @cell-mouse-enter="cellMouseEnter" @cell-mouse-leave="cellMouseLeave">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键id" align="center" prop="id" v-if="false"/>
          <el-table-column label="姓名" align="left" prop="name" width="80" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                <a target="_blank" style="color:#007bff;" v-if="scope.row.id!=null" @click="detailReport(scope.row.id)"> {{ scope.row.name }} </a>
                <span v-else> {{ scope.row.name }} </span>
            </template>
          </el-table-column>
          <el-table-column label="手机" align="center" prop="phone" width="150"/>
          <el-table-column label="跟进状态" align="left" prop="followStatus" width="110"/>
          <el-table-column label="线索来源" align="center" prop="cluesSources" width="100"/>
          <el-table-column label="责任人" align="center" prop="head" width="160"/>
          <el-table-column label="部门" align="center" prop="deptName" width="100" :show-overflow-tooltip="true"/>
          <el-table-column label="前负责人" align="center" prop="formerHead"  v-if="false"/>
          <el-table-column label="前所属部门" align="center" prop="formerDept"  v-if="false"/>
          <el-table-column label="最新跟进记录" align="left" prop="latestFollowRecords" width="240">
            <template slot-scope="scope">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" v-if="scope.row.hoverFlag" @click="addFollowRecords(scope.row)" v-hasPermi="['crm:clue:add']" >写跟进</el-button>
              <span v-else> {{ scope.row.latestFollowRecords}} </span>
            </template>
          </el-table-column>
          <el-table-column label="实际跟进记录" align="center" prop="realityFollowRecords" width="160" v-if="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.realityFollowRecords, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="未跟进天数" align="center" prop="notFollowDays" />
          <el-table-column label="下次跟进时间" align="center" prop="nextFollowTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.nextFollowTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="渠道" align="center" prop="channel" />
          <el-table-column label="转客户时间" align="center" prop="transferCustomerTime" width="120" v-if="false">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.transferCustomerTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最后通话时间" align="center" prop="lastCallTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastCallTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['crm:clue:edit']" >修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['crm:clue:remove']" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getMyList"/>
      </el-tab-pane>
      <el-tab-pane label="转客户线索" name="customer">
        <el-table v-loading="loading" :data="customerClueList" @selection-change="handleSelectionChange" @cell-mouse-enter="cellMouseEnter" @cell-mouse-leave="cellMouseLeave">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键id" align="center" prop="id" v-if="false"/>
          <el-table-column label="姓名" align="left" prop="name" width="80" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                <a target="_blank" style="color:#007bff;" v-if="scope.row.id!=null" @click="detailReport(scope.row.id)"> {{ scope.row.name }} </a>
                <span v-else> {{ scope.row.name }} </span>
            </template>
          </el-table-column>
          <el-table-column label="手机" align="center" prop="phone" width="150"/>
          <el-table-column label="跟进状态" align="left" prop="followStatus" width="110"/>
          <el-table-column label="线索来源" align="center" prop="cluesSources" width="100"/>
          <el-table-column label="责任人" align="center" prop="head" width="140"/>
          <el-table-column label="部门" align="center" prop="deptName" width="100"/>
          <el-table-column label="前负责人" align="center" prop="formerHead"  v-if="false"/>
          <el-table-column label="前所属部门" align="center" prop="formerDept"  v-if="false"/>
          <el-table-column label="最新跟进记录" align="left" prop="latestFollowRecords" width="240">
            <template slot-scope="scope">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" v-if="scope.row.hoverFlag" @click="addFollowRecords(scope.row)" v-hasPermi="['crm:clue:add']" >写跟进</el-button>
              <span v-else> {{ scope.row.latestFollowRecords}} </span>
            </template>
          </el-table-column>
          <el-table-column label="实际跟进记录" align="center" prop="realityFollowRecords" width="160" v-if="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.realityFollowRecords, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="未跟进天数" align="center" prop="notFollowDays" />
          <el-table-column label="下次跟进时间" align="center" prop="nextFollowTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.nextFollowTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="渠道" align="center" prop="channel" />
          <el-table-column label="转客户时间" align="center" prop="transferCustomerTime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.transferCustomerTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最后通话时间" align="center" prop="lastCallTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastCallTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['crm:clue:edit']" >修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['crm:clue:remove']" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getCustomerList"/>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改线索对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机" />
        </el-form-item>
        <el-form-item label="线索来源" prop="cluesSources">
          <el-select v-model="form.cluesSources" placeholder="请选择线索来源" style="width:320px;">
            <el-option
              v-for="item in cluesourcesOptions"
              :key="item.name"
              :label="item.name"
              :value="item.name"
              :disabled="item.checked == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="责任人" prop="head">
          <el-select v-model="form.head" placeholder="请选择责任人" style="width:320px;">
            <el-option
              v-for="item in userOptions"
              :key="item.userName"
              :label="item.nickName"
              :value="item.userName"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="部门" prop="deptId">
          <treeselect 
              style="float:left;width:320px;" 
              :multiple="false" 
              v-model="form.deptId" 
              :options="deptOptions" 
              :show-count="true" placeholder="请选择归属部门" />
        </el-form-item> -->
        <el-form-item label="渠道" prop="channel">
          <el-select v-model="form.channel" placeholder="请选择线索渠道" style="width:320px;">
            <el-option
              v-for="item in channelOptions"
              :key="item.name"
              :label="item.name"
              :value="item.name"
              :disabled="item.checked == 1"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加跟进记录对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="800px" append-to-body>
      <el-row :gutter="15">
        <el-form ref="formData" :model="formData" :rules="rulesFollow" size="medium" label-width="120px">
          <el-col :span="11">
            <el-form-item label="跟进类型" prop="followType">
              <el-select v-model="formData.followType" placeholder="请选择跟进类型" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in followTypeData" :key="index" :label="item.name"
                  :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跟进时间" prop="followTime">
              <el-date-picker v-model="formData.followTime"
                type="datetime" 
                :picker-options="pickerOption()" 
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                :style="{width: '100%'}" 
                placeholder="请选择跟进时间" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="跟进内容" prop="followContent">
              <el-input v-model="formData.followContent" type="textarea" placeholder="请输入跟进内容"
                :autosize="{minRows: 4, maxRows: 4}" :style="{width: '95%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="快速选择">
              <el-tag v-for="(item,index) in menuCateMap" 
                style="margin-left:5px;cursor: pointer;"
                :key="index" 
                :type="item.cssName" 
                @click.native="onClick(item.cssName)">{{item.label}}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="线索" prop="followClue">
              <el-input v-model="formData.followClue" :readonly="true" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跟进状态" prop="followStatus">
              <el-select v-model="formData.followStatus" placeholder="请选择跟进状态" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in followStatusOptions" :key="index" :label="item.name"
                  :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="下次跟进时间" prop="nextFollowTime">
              <el-date-picker v-model="formData.nextFollowTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{width: '90%'}" placeholder="请选择日期选择" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="textareasave">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数
import { listClue, getClue, delClue, addClue, updateClue, followRecords} from "@/api/crm/clue";
import { getUser, deptTreeSelect } from "@/api/system/user";
import { getDicts } from "@/api/system/dict/data";
import { getDate, getMonday, getMonth, getYear} from "@/api/tool/date";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Clue",
  components: { Treeselect },
  dicts: ['business_clue_sources', 'business_channel'],
  props: {
    value: {
      type: Array,
      default: function () {
        return [];
      }
    }
  },
  data() {
    return {
      followupstatusData: [],
      followuptimeData: [{"name":"全部","checked":"1"},{"name":"今天","checked":"0"},{"name":"昨天","checked":"0"},{"name":"本周","checked":"0"},{"name":"上周","checked":"0"},{"name":"本月","checked":"0"},{"name":"上月","checked":"0"},{"name":"自定义","checked":"0"}],
      followStatusOptions: [],
      channelData: [],
      channelOptions: [],
      cluesourcesData: [],
      cluesourcesOptions: [],
      followTypeData: [],
      menuCateMap: [
        { label: '电话通话中', value: 1, cssName: '电话通话中' },
        { label: '电话无人接听', value: 2, cssName: '电话无人接听' },
        { label: '听介绍直接挂断', value: 3, cssName: '听介绍直接挂断' },
        { label: '拒绝接听电话', value: 4, cssName: '拒绝接听电话' },
        { label: '让不要再打了,不需要', value: 5, cssName: '让不要再打了,不需要' },
      ],
      timeArr: '',
      selectDate: '',
      // 日期时间范围在一个月以内
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime()
          if (maxDate) {
            this.selectDate = ''
          }
        },
        disabledDate: (time) => {
         if (this.selectDate !== '') {
            const one = 30 * 24 * 3600 * 1000
            const minTime = this.selectDate - one
            const maxTime = this.selectDate + one
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      },
      textarea: "",
      taxtareaId:"",
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      followTime: new Date(),
      // 总条数
      total: 0,
      // CRM线索表格数据
      allClueList: [],
      myClueList: [],
      customerClueList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 用户选项
      userOptions: [],
      activeName: 'all',
      getAllClues: {
        pageNum: 1,
        pageSize: 5,
      },
      getMyClues: {
        pageNum: 1,
        pageSize: 5,
      },
      getCustomerClues: {
        pageNum: 1,
        pageSize: 5,
      },
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        phone: undefined,
        followStatus: undefined,
        cluesSources: undefined,
        head: undefined,
        heads: [],
        deptId: undefined,
        deptIds: [],
        formerHead: undefined,
        formerDept: undefined,
        latestFollowRecords: undefined,
        realityFollowRecordsSearch: undefined,
        notFollowDays: undefined,
        nextFollowTime: undefined,
        channel: undefined,
        transferCustomerTime: undefined,
        lastCallTime: undefined
      },
      // 表单参数
      form: {},
      formData: {
        clueId: undefined,
        followType: undefined,
        followTime: new Date(),
        followContent: undefined,
        followStatus: undefined,
        followClue: undefined,
        nextFollowTime: null,
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "12姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机不能为空", trigger: "blur" }
        ],
        followStatus: [
          { required: true, message: "跟进状态不能为空", trigger: "change" }
        ],
        cluesSources: [
          { required: true, message: "线索来源不能为空", trigger: "blur" }
        ],
        head: [
          { required: true, message: "责任人不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ],
        formerHead: [
          { required: true, message: "前负责人不能为空", trigger: "blur" }
        ],
        formerDept: [
          { required: true, message: "前所属部门不能为空", trigger: "blur" }
        ],
        latestFollowRecords: [
          { required: true, message: "最新跟进记录不能为空", trigger: "blur" }
        ],
        realityFollowRecords: [
          { required: true, message: "实际跟进记录不能为空", trigger: "blur" }
        ],
        notFollowDays: [
          { required: true, message: "未跟进天数不能为空", trigger: "blur" }
        ],
        nextFollowTime: [
          { required: true, message: "下次跟进时间不能为空", trigger: "blur" }
        ],
        channel: [
          { required: true, message: "渠道不能为空", trigger: "blur" }
        ],
        transferCustomerTime: [
          { required: true, message: "转客户时间不能为空", trigger: "blur" }
        ],
        lastCallTime: [
          { required: true, message: "最后通话时间不能为空", trigger: "blur" }
        ]
      },
      // 表单校验
      rulesFollow: {
        followType: [
          { required: true, message: "跟进类型不能为空", trigger: "blur" }
        ],
        followContent: [
          { required: true, message: "跟进内容不能为空", trigger: "blur" }
        ],
        followStatus: [
          { required: true, message: "跟进状态不能为空", trigger: "blur" }
        ],
        nextFollowTime: [
          { required: true, message: "下次跟进时间不能为空", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getDeptTree();
    this.getAllList();
    this.getUserInfo();
    this.getBusinessDicts();
    
  },
  methods: {
    checkPermi,
    checkRole,
    getUserInfo() {
      getUser().then(response => {
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
        this.userOptions = response.data.users;
      });
    },
    change(val) {
      this.$emit('input', val)
    },
    //责任人变化
    headChanged(value) {
      this.queryParams.heads = value;
      if ("all" == this.activeName) {
        this.getAllList();
      } else if ("my" == this.activeName) {
        this.getMyList();
      } else if ("customer" == this.activeName) {
        this.getCustomerList();
      }
    },
    getBusinessDicts() {
      this.getDicts("business_follow_status").then(response => {
        let businessFollowStatusData = response.data;
        for (var i=0;i<businessFollowStatusData.length;i++){ 
            if(businessFollowStatusData[i].dictLabel == '全部') {
              this.followupstatusData.push({name:businessFollowStatusData[i].dictLabel,checked:'1'});
            } else {
              this.followupstatusData.push({name:businessFollowStatusData[i].dictLabel,checked:'0'});
            }
            if(businessFollowStatusData[i].dictLabel == '全部' || businessFollowStatusData[i].dictLabel == '(空白)') {
              //
            } else {
              this.followStatusOptions.push({name:businessFollowStatusData[i].dictLabel,checked:'1'});
            }
        }
      });
      this.getDicts("business_channel").then(response => {
        let businessChannelData = response.data;
        for (var i=0;i<businessChannelData.length;i++){ 
            if(businessChannelData[i].dictLabel == '全部') {
              this.channelData.push({name:businessChannelData[i].dictLabel,checked:'1'});
            } else {
              this.channelData.push({name:businessChannelData[i].dictLabel,checked:'0'});
            }
            if(businessChannelData[i].dictLabel == '全部' || businessChannelData[i].dictLabel == '(空白)') {
              //
            } else {
              this.channelOptions.push({name:businessChannelData[i].dictLabel,checked:'0'});
            }
            
        }
      });
      this.getDicts("business_clue_sources").then(response => {
        let businessClueSourcesData = response.data;
        for (var i=0;i<businessClueSourcesData.length;i++){ 
            if(businessClueSourcesData[i].dictLabel == '全部') {
              this.cluesourcesData.push({name:businessClueSourcesData[i].dictLabel,checked:'1'});
            } else {
              this.cluesourcesData.push({name:businessClueSourcesData[i].dictLabel,checked:'0'});
            }
            if(businessClueSourcesData[i].dictLabel == '全部' || businessClueSourcesData[i].dictLabel == '(空白)') {
            } else {
              this.cluesourcesOptions.push({name:businessClueSourcesData[i].dictLabel,checked:'0'});
            }
        }
      });
      this.getDicts("business_follow_type").then(response => {
        let businessFollowTypeData = response.data;
        for (var i=0;i<businessFollowTypeData.length;i++){ 
            if(businessFollowTypeData[i].dictLabel == '全部') {
              this.followTypeData.push({name:businessFollowTypeData[i].dictLabel,checked:'1'});
            } else {
              this.followTypeData.push({name:businessFollowTypeData[i].dictLabel,checked:'0'});
            }
        }
      });
    },
    //部门选择
    selectPatenteeidsDept(node,instanceId) {
      if (!this.queryParams.deptIds) {
        this.queryParams.deptIds = [];
      }
      this.queryParams.deptIds.push(node.id);
      if ("all" == this.activeName) {
        this.getAllList();
      } else if ("my" == this.activeName) {
        this.getMyList();
      } else if ("customer" == this.activeName) {
        this.getCustomerList();
      }
    },
    //部门取消选择
    deSelectPatenteeidsDept(node,instanceId) {
      if (!this.queryParams.deptIds) {
        this.queryParams.deptIds = [];
      }
      let index = this.queryParams.deptIds.indexOf(node.id, 0);
      this.queryParams.deptIds.splice(index, 1);
      if ("all" == this.activeName) {
        this.getAllList();
      } else if ("my" == this.activeName) {
        this.getMyList();
      } else if ("customer" == this.activeName) {
        this.getCustomerList();
      }
    },
    //鼠标移入显示图标
    cellMouseEnter(row) {
      console.info("鼠标移入显示图标", this.ids);
      let Arr = JSON.parse(JSON.stringify(this.allClueList));
      for (let index = 0; index < Arr.length; index++) {
        const element = Arr[index];
        // 匹配滑过的当前行
        if (element.id === row.id) {
          element["hoverFlag"] = true;
        } else {
          element["hoverFlag"] = false;
        }
      }
      this.allClueList = JSON.parse(JSON.stringify(Arr));
      for (let index = 0; index < this.ids.length; index++) {
        console.info(this.ids[index]);
      }
    },
    //鼠标移出隐藏图标
    cellMouseLeave() {
      console.info("鼠标移出隐藏图标", this.ids);
      for (let index = 0; index < this.allClueList.length; index++) {
        const element = this.allClueList[index];
        element["hoverFlag"] = false;
      }
    },
    //点击图标方法
    addFollowRecords(row){
      this.reset1();
      console.info("填写跟进记录.........", row.id, row.name);
      this.formData.clueId = row.id;
      this.formData.followClue = row.name;
      this.formData.followTime = new Date(),
      this.open2 = true;
      this.title = "添加线索跟进记录";
    },
    onClick(tagvalue) {
      console.info(tagvalue);
      this.formData.followContent = tagvalue;
    },
        // 取消按钮
    onClose() {
      this.open2 = false;
      this.reset1();
    },
    // 线索详情
    detailReport(clueId) {
      console.log(clueId);
      this.$router.push({ path: '/crm/cluedetail/index', query: { clueId: clueId } })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询线索列表 */
    getAllList() {
      this.loading = true;
      listClue(this.queryParams, "all").then(response => {
        this.allClueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询我的线索
    getMyList() {
      this.loading = true;
      listClue(this.queryParams, "my").then(response => {
        this.myClueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询我的已转客户线索
    getCustomerList() {
      this.loading = true;
      listClue(this.queryParams, "customer").then(response => {
        this.customerClueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //tab页切换
    handleClick(tab) {
      console.info(tab.name);
      this.pbSel(tab.name)
    },
    pbSel(name) {
      let row = {};
      if (name =="all") {
        row = this.getAllClues;
      } else if (name =="my") {
        row = this.getMyClues;
      } else if (name =="customer") {
        row = this.getCustomerClues;
      }
      row.type = name;
      this.getClues(row);
    },
    getClues(row) {
      if (row.type == "all") {
        listClue(this.queryParams, row.type).then(response => {
          this.allClueList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
      if (row.type == "my") {
        listClue(this.queryParams, row.type).then(response => {
          this.myClueList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
      if (row.type == "customer") {
        listClue(this.queryParams, row.type).then(response => {
          this.customerClueList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    pickerOption() {
      // this.oldTime 是上一条数据的开始时间
      let date = new Date(this.followTime)
      let minutes = date.getMinutes() + 1
      // h和m 是将日期只取时分
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      let m = (minutes < 10 ? '0' + minutes : minutes);
      // pickerDate 判断当前选择时间是否等于上条数据时间
      // 若等于时，限制时间从00：00：00 - 上条数据开始时间，不等于时，24小时可选
      let pickerDate = date.toDateString() === new Date(this.form.followTime).toDateString() 
      return {
        // 日期限制
        disabledDate: (time) => {
          let old = this.oldTime
          return time.getTime() < new Date(old).getTime() - 86400000
        },
        // 时间限制
        selectableRange: pickerDate? h + m  + ':00 - 23:59:59' : '00:00:00 - 23:59:59'
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        phone: undefined,
        followStatus: undefined,
        cluesSources: undefined,
        createBy: undefined,
        createTime: undefined,
        head: undefined,
        deptId: undefined,
        formerHead: undefined,
        formerDept: undefined,
        latestFollowRecords: undefined,
        realityFollowRecords: undefined,
        notFollowDays: undefined,
        nextFollowTime: undefined,
        channel: undefined,
        transferCustomerTime: undefined,
        lastCallTime: undefined
      };
      this.resetForm("form");
    },
    reset1() {
      this.formData = {
        followContent: undefined, 
        followStatus: undefined, 
        nextFollowTime: undefined
      };
      this.resetForm("formData");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getAllList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加线索";
    },
    transferOthers() {
      console.info("转移给其他人");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getClue(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改线索";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateClue(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getAllList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addClue(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getAllList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },

    textareasave() {
      this.$refs["formData"].validate(valid => {
        if (valid) {
          console.info(this.formData.clueId, this.formData.followType, this.formData.followTime,this.formData.followContent, this.formData.followStatus,this.formData.followClue, this.formData.nextFollowTime);
          let data = '{"clueId":"' + this.formData.clueId + '", "followType":"' + this.formData.followType + '", "followTime":"' + this.formData.followTime + '", "followContent":"' + this.formData.followContent + '", "followStatus":"'+ this.formData.followStatus + '", "followClue":"' + this.formData.followClue + '", "flowType":"sales_flow", "nextFollowTime":"' + this.formData.nextFollowTime + '"}';
          followRecords(data).then(response => {
            console.info(1);
            this.open2 = false;
            this.getAllList();
            this.formData.clueId = '';
            this.formData.followType = '';
            this.formData.followTime = '';
            this.formData.followContent = '';
            this.formData.followStatus = '';
            this.formData.followClue = '';
            this.formData.nextFollowTime = '';
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除线索编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delClue(ids);
      }).then(() => {
        this.loading = false;
        this.getAllList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/clue/export', {
        ...this.queryParams
      }, `clue_${new Date().getTime()}.xlsx`)
    },
    //跟进状态
    changefollowupstatusColor(item,index) {
      console.info("跟进状态", this.activeName);
      const fuData = this.followupstatusData;
      let newFuData = [];
      let data1 = {};
      let searchfollowStatus = "";
      for (let i = 0; i < fuData.length; i++) {
        if (i == index) {
          if (fuData[i].checked == "0") {
            fuData[i].checked = "1";
          } else {
            fuData[i].checked = "0";
          }
        }
        data1 = {name:fuData[i].name, checked:fuData[i].checked};
        newFuData.push(data1);
      }
      if (index > 0 && index < newFuData.length) {
        newFuData[0].checked = "0";
      }
      if (index == 0) {
        for (let i = 1; i < newFuData.length; i++) {
          newFuData[i].checked = "0";
        }
        newFuData[0].checked = "1";
      }
      if (index == (newFuData.length - 1)) {
        for (let i = 1; i < newFuData.length; i++) {
          newFuData[i].checked = "0";
        }
        newFuData[0].checked = "1";
      }
      for (let i = 1; i < newFuData.length; i++) {
        if (newFuData[i].checked == "1") {
          if (searchfollowStatus != '') {
            searchfollowStatus = searchfollowStatus + "," + newFuData[i].name;
          } else {
            searchfollowStatus = newFuData[i].name;
          }
        }
      }
      this.followupstatusData = newFuData;
      this.queryParams.followStatus = searchfollowStatus;
      if ("all" == this.activeName) {
        this.getAllList();
      } else if ("my" == this.activeName) {
        this.getMyList();
      } else if ("customer" == this.activeName) {
        this.getCustomerList();
      }
    },
    //时间
    changefollowuptimeColor(item,index) {
      const fuData = this.followuptimeData;
      let newFuData = [];
      let data1 = {};
      let searchfollowuptime = "";
      for (let i = 0; i < fuData.length; i++) {
        if (i == index) {
          if (fuData[i].checked == "0") {
            fuData[i].checked = "1";
          }
        } else {
          fuData[i].checked = "0";
        }
        data1 = {name:fuData[i].name, checked:fuData[i].checked};
        newFuData.push(data1);
      }
      this.followuptimeData = newFuData;
      console.info("当前选项-", item.name);
      if (item.name == '今天') {
        let cDate = getDate(0);
        let cDateStart = cDate + " 00:00:00";
        let cDateEnd = cDate + " 23:59:59";
        this.queryParams.realityFollowRecordsSearch = [cDateStart,cDateEnd];
      }
      if (item.name == '昨天') {
        let cDate = getDate(-1);
        let cDateStart = cDate + " 00:00:00";
        let cDateEnd = cDate + " 23:59:59";
        this.queryParams.realityFollowRecordsSearch = [cDateStart,cDateEnd];
      }
      if (item.name == '本周') {
        let cDate = getMonday("s",0);
        let cDate1 = getMonday("e",0);
        let cDateStart = cDate + " 00:00:00";
        let cDateEnd = cDate1 + " 23:59:59";
        this.queryParams.realityFollowRecordsSearch = [cDateStart,cDateEnd];
      }
      if (item.name == '上周') {
        let cDate = getMonday("s",-1);
        let cDate1 = getMonday("e",-1);
        let cDateStart = cDate + " 00:00:00";
        let cDateEnd = cDate1 + " 23:59:59";
        this.queryParams.realityFollowRecordsSearch = [cDateStart,cDateEnd];
      }
      if (item.name == '本月') {
        let cDate = getMonth("s",0);
        let cDate1 = getMonth("e",0);
        let cDateStart = cDate + " 00:00:00";
        let cDateEnd = cDate1 + " 23:59:59";
        this.queryParams.realityFollowRecordsSearch = [cDateStart,cDateEnd];
      }
      if (item.name == '上月') {
        let cDate = getMonth("s",-1);
        let cDate1 = getMonth("e",-1);
        let cDateStart = cDate + " 00:00:00";
        let cDateEnd = cDate1 + " 23:59:59";
        this.queryParams.realityFollowRecordsSearch = [cDateStart,cDateEnd];
      }
      console.info(this.queryParams.realityFollowRecordsSearch);
      //this.queryParams.followStatus = searchfollowuptime;
      if ("all" == this.activeName) {
        this.getAllList();
      } else if ("my" == this.activeName) {
        this.getMyList();
      } else if ("customer" == this.activeName) {
        this.getCustomerList();
      }
    },
    
    //渠道
    changechannelColor(item,index) {
      console.info("渠道", this.activeName);
      const fuData = this.channelData;
      let newFuData = [];
      let data1 = {};
      let searchChannel = "";
      for (let i = 0; i < fuData.length; i++) {
        if (i == index) {
          if (fuData[i].checked == "0") {
            fuData[i].checked = "1";
          } else {
            fuData[i].checked = "0";
          }
        }
        data1 = {name:fuData[i].name, checked:fuData[i].checked};
        newFuData.push(data1);
      }
      if (index > 0 && index < newFuData.length) {
        newFuData[0].checked = "0";
      }
      if (index == 0) {
        for (let i = 1; i < newFuData.length; i++) {
          newFuData[i].checked = "0";
        }
        newFuData[0].checked = "1";
      }
      if (index == (newFuData.length - 1)) {
        for (let i = 1; i < newFuData.length; i++) {
          newFuData[i].checked = "0";
        }
        newFuData[0].checked = "1";
      }
      for (let i = 1; i < newFuData.length; i++) {
        if (newFuData[i].checked == "1") {
          if (searchChannel != '') {
            searchChannel = searchChannel + "," + newFuData[i].name;
          } else {
            searchChannel = newFuData[i].name;
          }
        }
      }
      this.channelData = newFuData;
      this.queryParams.channel = searchChannel;
      if ("all" == this.activeName) {
        this.getAllList();
      } else if ("my" == this.activeName) {
        this.getMyList();
      } else if ("customer" == this.activeName) {
        this.getCustomerList();
      }
    },
    //线索来源
    changecluesourcesColor(item,index) {
      console.info("线索来源", this.activeName);
      const fuData = this.cluesourcesData;
      let newFuData = [];
      let data1 = {};
      let cluesources = "";
      for (let i = 0; i < fuData.length; i++) {
        if (i == index) {
          if (fuData[i].checked == "0") {
            fuData[i].checked = "1";
          } else {
            fuData[i].checked = "0";
          }
        }
        data1 = {name:fuData[i].name, checked:fuData[i].checked};
        newFuData.push(data1);
      }
      if (index > 0 && index < newFuData.length) {
        newFuData[0].checked = "0";
      }
      if (index == 0) {
        for (let i = 1; i < newFuData.length; i++) {
          newFuData[i].checked = "0";
        }
        newFuData[0].checked = "1";
      }
      if (index == (newFuData.length - 1)) {
        for (let i = 1; i < newFuData.length; i++) {
          newFuData[i].checked = "0";
        }
        newFuData[0].checked = "1";
      }

      for (let i = 1; i < newFuData.length; i++) {
        if (newFuData[i].checked == "1") {
          if (cluesources != '') {
            cluesources = cluesources + "," + newFuData[i].name;
          } else {
            cluesources = newFuData[i].name;
          }
        }
      }
      this.cluesourcesData = newFuData;
      this.queryParams.cluesSources = cluesources;
      if ("all" == this.activeName) {
        this.getAllList();
      } else if ("my" == this.activeName) {
        this.getMyList();
      } else if ("customer" == this.activeName) {
        this.getCustomerList();
      }
    },
    choosely(n,value){
        if(this.chooseAfterValue.indexOf( value )!=-1) {
            this.chooseAfterValue.splice( this.chooseAfterValue.indexOf( value ), 1 )
        } else {
            this.chooseAfterValue.push(value)
        }
    },
  }
};
</script>
<style scoped>
.search-condition-div {
  height:40px;
}
.search-condition-div span {
  margin-left: 15px;
  cursor: pointer;
  border-radius: 5px;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
  padding-bottom: 10px;
}
.follow-up-status-all {
  margin-left: 5px;
  background-color: #fff2ea;
  color: #FC8352;
}
.active {
  background-color: #fff2ea;
  color: #FC8352;
}
</style>
